#ifndef HIDABLETABWIDGET_H
#define HIDABLETABWIDGET_H

#include <QTabWidget>
#include <QTabBar>
#include <QWidget>
#include <QMouseEvent>

class TabBar : public QTabBar {

    private:
        bool midButtonClose;

    public:
        TabBar(QWidget *parent = 0, bool midButtonClose = true) : QTabBar(parent) {
            setMidButtonCloseable(midButtonClose);
        }

        bool isMidButtonCloseable() const {
            return midButtonClose;
        }

        void setMidButtonCloseable(bool midButtonClose) {
            this->midButtonClose = midButtonClose;
        }

    protected:
        void mousePressEvent(QMouseEvent *event) {
            if (isMidButtonCloseable() && (event->button() == Qt::RightButton || event->button() == Qt::MiddleButton)) {
                tabCloseRequested(tabAt(event->pos()));
            }
            QTabBar::mousePressEvent(event);
        }

};


class TabWidget : public QTabWidget {

    private:
        TabBar *bar;

    public:

        TabWidget(QWidget *parent = 0, bool midButtonClose = true) : QTabWidget(parent) {
            bar = new TabBar(this, midButtonClose);
            setTabBar(bar);
        }

        void showTabBar(bool show) {
            tabBar()->setVisible(show);
        }

        TabBar *tabBar() {
            return bar;
        }

    protected:

        void tabInserted(int index) {
            QTabWidget::tabInserted(index);
            if(count() == 1) {
                showTabBar(false);
            } else {
                showTabBar(true);
            }
        }

        void tabRemoved(int index) {
            QTabWidget::tabInserted(index);
            if(count() == 1) {
                showTabBar(false);
            } else {
                showTabBar(true);
            }
        }

};


#endif // HIDABLETABWIDGET_H
